<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? $t('page.system.menu.edit') : $t('page.system.menu.add')"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item
        :label="$t('page.system.menu.parentId')"
        prop="parentId"
      >
        <el-tree-select
          v-model="form.parentId"
          :data="menuTreeData"
          :props="{ label: 'menuName', value: 'id', children: 'children' }"
          :placeholder="$t('page.system.menu.selectParentMenu')"
          check-strictly
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.menu.menuName')"
        prop="menuName"
      >
        <el-input
          v-model="form.menuName"
          :placeholder="$t('page.system.menu.form.menuNameRequired')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.menu.path')"
        prop="path"
      >
        <el-input
          v-model="form.path"
          :placeholder="$t('page.system.menu.form.pathRequired')"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.menu.component')"
        prop="component"
      >
        <el-input
          v-model="form.component"
          :placeholder="$t('page.system.menu.form.componentRequired')"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.menu.perms')"
        prop="perms"
      >
        <el-input
          v-model="form.perms"
          :placeholder="$t('page.system.menu.form.permsRequired')"
          maxlength="100"
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.menu.status')"
        prop="status"
      >
        <el-radio-group v-model="form.status">
          <el-radio label="0">{{ $t('page.system.menu.normal') }}</el-radio>
          <el-radio label="1">{{ $t('page.system.menu.disabled') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('page.system.menu.cancel') }}
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ $t('page.system.menu.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRadio,
  ElRadioGroup,
  ElTreeSelect,
} from 'element-plus';

import type { MenuFormData, MenuTreeNode } from '#/api/system/menu';
import { createMenuApi, getMenuTreeApi, updateMenuApi } from '#/api/system/menu';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  formData: Partial<MenuFormData>;
  isEdit: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const formRef = ref<FormInstance>();
const loading = ref(false);
const menuTreeData = ref<MenuTreeNode[]>([]);

// 表单数据
const form = reactive<MenuFormData>({
  menuName: '',
  path: '',
  component: '',
  status: '0',
  perms: '',
  parentId: 0,
});

// 表单验证规则
const rules: FormRules = {
  menuName: [
    { required: true, message: $t('page.system.menu.form.menuNameRequired'), trigger: 'blur' },
    { min: 2, max: 50, message: $t('page.system.menu.form.menuNameLength'), trigger: 'blur' },
  ],
  path: [
    { required: true, message: $t('page.system.menu.form.pathRequired'), trigger: 'blur' },
  ],
  component: [
    { required: true, message: $t('page.system.menu.form.componentRequired'), trigger: 'blur' },
  ],
  perms: [
    { required: true, message: $t('page.system.menu.form.permsRequired'), trigger: 'blur' },
  ],
  status: [
    { required: true, message: $t('page.system.menu.form.statusRequired'), trigger: 'change' },
  ],
};

// 获取菜单树数据
const getMenuTreeData = async () => {
  try {
    const data = await getMenuTreeApi();
    // 添加顶级菜单选项
    menuTreeData.value = [
      {
        id: 0,
        menuName: $t('page.system.menu.topLevel'),
        children: data,
      },
    ];
  } catch (error) {
    console.error('获取菜单树失败:', error);
  }
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      getMenuTreeData();
    }
  }
);

// 监听 formData 变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(form, {
        id: newData.id,
        menuName: newData.menuName || '',
        path: newData.path || '',
        component: newData.component || '',
        status: newData.status || '0',
        perms: newData.perms || '',
        parentId: newData.parentId ?? 0,
      });
    }
  },
  { immediate: true, deep: true }
);

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    loading.value = true;
    
    if (props.isEdit) {
      await updateMenuApi(form);
      ElMessage.success($t('page.system.menu.message.updateSuccess'));
    } else {
      await createMenuApi(form);
      ElMessage.success($t('page.system.menu.message.createSuccess'));
    }
    
    emit('submit');
    handleClose();
  } catch (error) {
    console.error('提交表单失败:', error);
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 
